//
//  CTVSystemFeedback.m
//  Channltv
//
//  Created by Bruno Keymolen on 19/09/07.
//  Copyright 2007 channl.tv. All rights reserved.
//

#import "CTVSystemFeedback.h"
#import "CTVConfig.h"
#import "CTVUser.h"

@implementation CTVSystemFeedback

-(id)init{
	self = [super init];
	return self;
}

-(void)dealloc{
	if(m_connection){
		[m_connection release];
	}
	
	[super dealloc];
}




+(void)rateClip:(CTVClip*)clip rate:(int)rate{
		NSLog(@"Rate: %@ - %d", [clip clipID],  rate);
		NSString* url = [NSString stringWithFormat:@"http://%@/api/rate?guid=%@&rating=%d", [[CTVConfig GetInstance] CTVServer], [clip clipID], rate];
		
		CTVSystemFeedback* fb = [[CTVSystemFeedback alloc] init];
			
		[fb asyncGetURLString:url];
}


+(void)systemClipFeedBackWithMessage:(NSString*)message andClipID:(NSString*)clipID{
	CTVSystemFeedback* fb = [[CTVSystemFeedback alloc] init];
	
	CTVUser* activeUser =[[CTVConfig GetInstance] activeUser];
	//Clip
	NSMutableDictionary* fields = [NSMutableDictionary dictionaryWithCapacity:5];
	[fields setObject:[activeUser uid] forKey:@"viewer_id"];
	[fields setObject:clipID forKey:@"guid"];
	[fields setObject:message forKey:@"message"];
	[fields setObject:@"AppleTV" forKey:@"system_type"];
		
	NSString* url = [NSString stringWithFormat:@"http://%@/system_feedbacks.xml", [[CTVConfig GetInstance] CTVServer]];	
	[fb asyncPostToURLString:url usingForm:nil andFields:fields postXML:TRUE];	
}


+(void)systemFeedBackWithMessage:(NSString*)message{
	CTVSystemFeedback* fb = [[CTVSystemFeedback alloc] init];

	CTVUser* activeUser =[[CTVConfig GetInstance] activeUser];
	//Clip
	NSMutableDictionary* fields = [NSMutableDictionary dictionaryWithCapacity:4];
	[fields setObject:[activeUser uid] forKey:@"viewer_id"];
	[fields setObject:message forKey:@"message"];
	[fields setObject:@"AppleTV" forKey:@"system_type"];
		
	NSString* url = [NSString stringWithFormat:@"http://%@/system_feedbacks.xml", [[CTVConfig GetInstance] CTVServer]];	
	[fb asyncPostToURLString:url usingForm:nil andFields:fields postXML:TRUE];	
}


-(int)asyncGetURLString:(NSString*)urlString{
	//Async Get
	NSURL* nurl = [NSURL URLWithString:urlString];
	NSMutableURLRequest* urlRequest=[NSMutableURLRequest requestWithURL:nurl
							cachePolicy:NSURLRequestReloadIgnoringCacheData
							timeoutInterval:15.0];
	
	[urlRequest setHTTPMethod:@"GET"];

	//Modify some Headers
	[urlRequest setValue:[[CTVConfig GetInstance] userAgent] forHTTPHeaderField:@"User-Agent"];

	//[urlRequest setHTTPBody:[urlString dataUsingEncoding:NSASCIIStringEncoding]];

	//Get it
	m_connection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

	if (m_connection == nil) {
		return -1;
	}	
	
	//The get is ongoing
	return 0;
	
}


-(int)asyncPostToURLString:(NSString*)urlString usingForm:(NSString*)formName andFields:(NSDictionary*)dict postXML:(BOOL)postXml{

	//Async Post
	NSURL* nurl = [NSURL URLWithString:urlString];
	NSMutableURLRequest* urlRequest=[NSMutableURLRequest requestWithURL:nurl
							cachePolicy:NSURLRequestReloadIgnoringCacheData
							timeoutInterval:5.0];
	
	[urlRequest setHTTPMethod:@"POST"];

	//Modify some Headers
	[urlRequest setValue:[[CTVConfig GetInstance] userAgent] forHTTPHeaderField:@"User-Agent"];

	if(postXml == TRUE){
		[urlRequest setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
	}
	
	//Create the content data
	NSMutableString* content;

	if(postXml == FALSE){
		content = [NSMutableString stringWithString:@"_method=put"];
		NSEnumerator* keyEnum = [dict keyEnumerator];
		NSString *field, *data;
		while(field = [keyEnum nextObject]){
			data = [dict objectForKey:field];
			[content appendString:@"&"];
			[content appendString:field];
			[content appendString:@"="];
			[content appendString:data];		
		}
		[content appendString:@"&_commit=Append"];
	}else{
		NSEnumerator* keyEnum = [dict keyEnumerator];
		NSString *field, *data;
		content = [NSMutableString stringWithString:@"<system_feedback>"];
		while(field = [keyEnum nextObject]){
			data = [dict objectForKey:field];
			[content appendFormat:@"<%@>%@</%@>", field, data, field];
		}	
		[content appendString:@"</system_feedback>"];	
		
	}
		
	[urlRequest setHTTPBody:[content dataUsingEncoding:NSASCIIStringEncoding]];

	//Post it
	m_connection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

	if (m_connection == nil) {
		return -1;
	}	
	
	//The download is ongoing
	return 0;

}


/* NSURLConnection Delegates */
- (void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
	//we have to (re)login first
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	[self autorelease];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
	//Ignore, we did a post and forget about it...
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	//Ignore, we did a post and forget about it...
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
	return nil;
}

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{
	//Oops, we have a redirect, modify the headers to our needs
	NSMutableURLRequest* urlRequest= [request mutableCopyWithZone:nil];	
		
	//Modify some Headers
	[urlRequest setValue:[[CTVConfig GetInstance] userAgent] forHTTPHeaderField:@"User-Agent"];	
	
	return urlRequest;

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	[self autorelease];
}



@end
